<?php
require __DIR__ . '/vendor/autoload.php';
use Waybill\Wlhy;

const baseurl = "https://heilongjiang.wlhy.org.cn"; // 测试环境-信息上报接口
//const baseurl = "http://116.182.4.67:50033/platform"; // 正式环境-信息上报接口
const account =  "23107008"; // 账号
const passwd = "Xi6S6l3U"; // 密码

/**
 * 打印输出方法
 * @param $data
 * @return void
 */
function p($data = []): void
{
  if (is_array($data) || is_object($data)) {
    echo "<pre>";
    print_r($data);
    echo "</pre>\n";
  } else {
    echo $data, PHP_EOL;
  }
}

/**
 * 处理函数
 * @param $type
 * @return void
 */
function deal($type = "", $config = [])
{
  //实例化类
  $waybill = new Wlhy($config);
  switch ($type) {
    case "getPubKey":
      //获取公钥
      $reqData = [];
      $res = $waybill->getPubKey("uploadFile", $reqData);
      if($res["code"] == 1){
        //记录日志
        p($res["data"]["result"]); // 6d04b614-2484-40f6-8a36-ebd9ed595b00.jpg、b7edacc0-79b3-443d-b2e5-93bdd26a971b.jpg
      } else {
        //记录日志
        p($res);
      }
      break;
    case "transport":
      break;
  }
}

/**
 * 获取toke：有效期2h
 * @return array
 */
function getToken($config = [], $publicKey = ""):array
{
  //暂存token_wlhy.json，到时改为redis存储
  $tokenFile = "./token_wlhy.json";
  if (file_exists($tokenFile) && $token = file_get_contents($tokenFile)) {
    if (!empty($token)) {
      return json_decode($token, true);
    }
  }

  //获取token
  $waybill = new Wlhy($config);
  $res = $waybill->getToken($publicKey);
  if($res["code"] != 1){
    //错误记录日志
    p($res);

    //返回
    return [
      "token" => "",
      "user" => [
        "id" => 0
      ]
    ];
  }

  //暂存token.txt，到时改为redis存储
  file_put_contents($tokenFile, json_encode($res["data"]["result"]));
  return $res["data"]["result"];
}

//配置信息
$config = [
  "baseurl" => baseurl,
  "account" => account,
  "passwd" => sha1(passwd)
];

//获取公钥
//实例化类
$waybill = new Wlhy($config);
$res = $waybill->getPubKey();
if($res["code"] != 1){
  //记录日志
  p($res);
  return "公钥异常";
}
$publicKey = $res["data"]["result"]["publicKey"];
p($publicKey);

//获取token
$token = getToken($config, $publicKey);
if(empty($token["token"])){
  return "token异常";
}
$config["token"] = $token;

//文件上传接口：上传电子运单、车辆信息、驾驶员信息中相关图片文件(备注:文件大小需要小于2M)
//deal("getPubKey", $config);